from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import List
from datetime import datetime
from app.database.database import get_db
from app.models import models
from app.schemas import schemas

router = APIRouter(prefix="/api/wineries", tags=["wineries"])

@router.get("/", response_model=schemas.Page)
def get_wineries(page: int = Query(1, ge=1), size: int = Query(10, ge=1, le=200), db: Session = Depends(get_db)):
    q = db.query(models.Winery)
    total = q.count()
    orm_items = q.offset((page-1)*size).limit(size).all()
    items = [schemas.Winery.model_validate(i) for i in orm_items]
    return {"total": total, "page": page, "size": size, "items": items}

@router.post("/", response_model=schemas.Winery)
def create_winery(winery: schemas.WineryCreate, db: Session = Depends(get_db)):
    db_winery = models.Winery(**winery.dict())
    db.add(db_winery)
    db.commit()
    db.refresh(db_winery)
    return db_winery

@router.get("/{winery_id}", response_model=schemas.Winery)
def get_winery(winery_id: int, db: Session = Depends(get_db)):
    winery = db.query(models.Winery).filter(models.Winery.id == winery_id).first()
    if winery is None:
        raise HTTPException(status_code=404, detail="Winery not found")
    return winery

@router.put("/{winery_id}", response_model=schemas.Winery)
def update_winery(winery_id: int, winery: schemas.WineryCreate, db: Session = Depends(get_db)):
    db_winery = db.query(models.Winery).filter(models.Winery.id == winery_id).first()
    if db_winery is None:
        raise HTTPException(status_code=404, detail="Winery not found")
    for key, value in winery.dict().items():
        setattr(db_winery, key, value)
    db.commit(); db.refresh(db_winery)
    return db_winery

@router.delete("/{winery_id}")
def delete_winery(winery_id: int, db: Session = Depends(get_db)):
    winery = db.query(models.Winery).filter(models.Winery.id == winery_id).first()
    if winery is None:
        raise HTTPException(status_code=404, detail="Winery not found")
    db.delete(winery); db.commit()
    return {"message": "Winery deleted successfully"}

@router.post("/bulk-delete")
def bulk_delete(ids: List[int], db: Session = Depends(get_db)):
    deleted = db.query(models.Winery).filter(models.Winery.id.in_(ids)).delete(synchronize_session=False)
    db.commit()
    return {"deleted": deleted}
